import { StorageKeys } from './constant';


export function removeWxLoginCode() {
	wx.removeStorageSync(StorageKeys.WxLoginCode);
}

export function checkSession() : Promise<boolean> {
	return new Promise(resove => {
		wx.checkSession({
			success() {
				resove(true);
			},
			fail() {
				wx.removeStorageSync(StorageKeys.WxLoginCode);
				resove(false);
			}
		});
	})
}

export function login() : Promise<string> {
	return new Promise(resove => {
		wx.login({
			success(result) {
				wx.setStorageSync<string>(StorageKeys.WxLoginCode, result.code);
				resove(result.code);
			}
		});
	})
}

export const wxLogin = login;


export function getLoginCode() : Promise<string> {
	return new Promise(resove => {
		checkSession().then((flag : boolean) => {
			if (flag) {
				try {
					const loginCode = wx.getStorageSync(StorageKeys.WxLoginCode);
					if (loginCode) {
						return resove(loginCode);
					}
				} catch (e) {
					//
				}
			}
			login().then((loginCode : string) => {
				resove(loginCode);
			});
		})
	})
}


export function openDocument(url : string) {
	wx.showLoading({ title: '下载中...' });
	wx.downloadFile({
		url,
		success: (res) => {
			if (res.statusCode !== 200) {
				wx.showToast({ mask: true, title: '下载失败，请稍后再试', icon: "none" })
				return;
			}
			const filePath = res.tempFilePath;
			wx.openDocument({
				filePath: filePath,
				success: (res) => {
					console.log('openDocument.success', res);
				}
			})
		},
		fail: () => {
			wx.showToast({ mask: true, title: '下载失败，请稍后再试', icon: "none" })
		},
		complete: (res) => {
			console.log('downloadFile.complete', res);
			wx.hideLoading();
		}
	})
}